#include "soc.h"
#include "gsm.h"
#include "ble.h"
#include "ble_gap.h"
#include "ble_hci.h"

typedef struct control_obj_t
{
    uint8_t cur_key;
    uint8_t cam_status;
    uint8_t led_red_blink;
} CONTROL_OBJ_T;

CONTROL_OBJ_T g_control = 
{
    .cur_key = 0,
    .cam_status = 0,
    .led_red_blink = 0,
};


uint8_t get_key(void)
{
    static uint8_t old_key1=1;
    static uint8_t old_key2=1;
    if( old_key1 != Ttl_Io_Get( PIN_KEY1) ) {
        old_key1 = Ttl_Io_Get( PIN_KEY1);
        if( old_key1 == 1 ) {
            return 1;
        }
    }
    if( old_key2 != Ttl_Io_Get( PIN_KEY1) ) {
        old_key2 = Ttl_Io_Get( PIN_KEY1);
        if( old_key2 == 1 ) {
            return 2;
        }
    }
    return 0;
}

void control_cam( void )
{
	if( Ttl_Io_Get( PIN_KEY1 ) ) {
		Ttl_Io_Set( PIN_CAM_EN, 0 );
		Ttl_Io_Set( PIN_LED_BLUE, 1 );
	} else {
		Ttl_Io_Set( PIN_CAM_EN, 1 );
		Ttl_Io_Set( PIN_LED_BLUE, 0 );
	}
//    if( g_control.cur_key == 1 ) {
//        g_control.cam_status = !(g_control.cam_status);
//    }
//    if( g_control.cam_status == 0 ) {
//        /* close cam */
//        Ttl_Io_Set( PIN_LED_BLUE, 1 );
//        Ttl_Io_Set( PIN_CAM_EN, 0 );
//    } else {
//        /* open cam */
//        Ttl_Io_Set( PIN_LED_BLUE, 0 );
//        Ttl_Io_Set( PIN_CAM_EN, 1 );
//    }
}

void Control_Set_Led_Blink( uint8_t en )
{
    g_control.led_red_blink = en;
}

void control_led_show( void )
{
    static uint8_t cnt=0;
    if( g_control.led_red_blink == 0 ) {
        // off
        Ttl_Io_Set( PIN_LED_RED, 1 );
        cnt = 0;
        return;
    }
    if( cnt & 1 ) {
        Ttl_Io_Set( PIN_LED_RED, 1 );
    } else {
        Ttl_Io_Set( PIN_LED_RED, 0 );
    }
    cnt++;
}
extern volatile uint8_t ble_stop_flag;
extern volatile uint8_t ble_restart_flag;
extern void ble_reastart_func( void );
extern uint16_t                         m_conn_handle;
void Control_Loop( void )
{
    g_control.cur_key = get_key();
    control_cam();
    control_led_show();
		if( ble_stop_flag && (m_conn_handle == BLE_CONN_HANDLE_INVALID) ) {
					ble_stop_flag = 0;
					sd_ble_gap_connect_cancel();
					sd_ble_gap_disconnect(m_conn_handle,BLE_HCI_CONN_INTERVAL_UNACCEPTABLE);
					sd_ble_gap_scan_stop();
		}
		if( ble_restart_flag ) {
			ble_restart_flag= 0;
			ble_reastart_func();
		}
}
